package com.ezbuy.common.bean;

import java.util.ArrayList;
import java.util.List;

/**
 * ezbuy 2018/12/2 上午11:01
 */
public class MacroBean {

    private String name;
    private List<MacroBean> childs = new ArrayList<>();

    private int level;//这个属性只是方便打印,不是数据模型真正需要的

    public MacroBean(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<MacroBean> getChilds() {
        return childs;
    }

    public void setChilds(List<MacroBean> childs) {
        this.childs = childs;
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    public void addChild(MacroBean child) {
        if (childs.contains(child)) {
            return;
        }
        childs.add(child);
        child.level = this.level + 1;
    }

    private void print() {
        System.out.println(name);
        StringBuilder preFix = new StringBuilder();
        printChild(childs, preFix);
    }

    private void printChild(List<MacroBean> childs, StringBuilder preFix) {
        for (MacroBean child : childs) {
            StringBuilder clone = new StringBuilder(preFix);
            clone.append("-");
            System.out.println(clone.toString() + child.name);
            printChild(child.childs, clone);
        }
    }

    public void build() {
        tobuildNode(this);
        buildNode(childs, this);
    }

    public void buildNode(List<MacroBean> childs, MacroBean parent) {
        String preFix = getPreFix(parent);
        System.out.println(preFix + "[");
        System.out.println(preFix + "\t" + parent.name);
        if (childs != null) {
            for (MacroBean child : childs) {
                buildNode(child.childs, child);
            }
        }
        System.out.println(preFix + "]");
    }

    private void tobuildNode(MacroBean macroBean) {
        System.out.println(getPreFix(macroBean) + macroBean.name);
    }

    private String getPreFix(MacroBean macroBean) {
        StringBuilder preFix = new StringBuilder();
        for (int i = 0; i < macroBean.level; i++) {
            preFix.append("\t");
        }
        return preFix.toString();
    }

    public static MacroBean newInstance() {
        MacroBean root = new MacroBean("root");
        MacroBean child1 = new MacroBean("child1");
        MacroBean child2 = new MacroBean("child2");
        MacroBean child3 = new MacroBean("child3");
        MacroBean child31 = new MacroBean("child31");
        MacroBean child32 = new MacroBean("child32");
        MacroBean child33 = new MacroBean("child33");

        root.addChild(child1);
        root.addChild(child2);
        root.addChild(child3);

        child3.addChild(child31);
        child3.addChild(child32);
        child3.addChild(child33);
        return root;
    }

}
